<template>
  <el-form label-width="100px">
    <el-form-item label="SPU名称">
      <el-input
        placeholder="请你输入SPU名称"
        v-model="SpuParams.spuName"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select style="width: 150px" v-model="SpuParams.tmId">
        <el-option
          v-for="(item, index) in AllTradeMark"
          :key="item.id"
          :label="item.tmName"
          :value="item.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input
        type="textarea"
        placeholder="请你输入SPU描述"
        v-model="SpuParams.description"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU图片">
      <el-upload
        v-model:file-list="imgList"
        action="/api/admin/product/fileUpload"
        list-type="picture-card"
        :headers="headers"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :before-upload="handlerUpload"
      >
        <el-icon>
          <Plus />
        </el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
    </el-form-item>
    <el-form-item label="SPU销售属性" size="normal">
      <!-- 展示销售属性的下拉菜单 -->
      <el-select
        style="width: 150px"
        v-model="unSelectSalkeAttrIdAndName"
        :placeholder="
          unSelectSaleAttr.length
            ? `还未选择${unSelectSaleAttr.length}个`
            : '无'
        "
      >
        <el-option
          v-for="(item, index) in unSelectSaleAttr"
          :key="item.id"
          :label="item.name"
          :value="`${item.id}:${item.name}`"
        ></el-option>
      </el-select>
      <el-button
        style="margin-left: 10px"
        type="primary"
        size="default"
        icon="Plus"
        @click="addSaleAttr"
        :disabled="unSelectSalkeAttrIdAndName ? false : true"
      >
        添加属性
      </el-button>
      <!-- table展示销售属性与属性值的地方 -->
      <el-table border style="margin: 10px 0px" :data="saleAttr">
        <el-table-column
          label="序号"
          type="index"
          align="center"
          width="80px"
        ></el-table-column>
        <el-table-column
          label="销售属性名字"
          width="120px"
          prop="saleAttrName"
        ></el-table-column>
        <el-table-column label="销售属性值">
          <!-- row:即为当前SPU已有的销售属性对象 -->
          <template #="{ row, $index }">
            <el-tag
              v-for="(item, index) in row.spuSaleAttrValueList"
              :key="item.id"
              style="margin: 5px"
              @close="row.spuSaleAttrValueList.splice(index, 1)"
              closable
            >
              {{ item.saleAttrValueName }}
            </el-tag>
            <el-input
              v-if="row.flag == true"
              v-model="row.saleAttrvalue"
              @blur="toLook(row)"
              placeholder="请输入相应的属性值"
              size="small"
              style="width: 150px"
            ></el-input>
            <el-button
              v-else
              @click="toEdito(row)"
              type="primary"
              icon="Plus"
              size="small"
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120px">
          <template #="{ row, $index }">
            <el-button
              type="primary"
              icon="Delete"
              size="small"
              color="#f5a4a4"
              @click="saleAttr.splice($index, 1)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="default" @click="save">保存</el-button>
      <el-button type="primary" size="default" @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import type {
  SpuData,
  TradeMarkData,
  SpuImg,
  SpuSaleValue,
  BaseSaleAttr,
  AllTradeMarkResponseData,
  SpuImgResponseData,
  SpuSaleResponseData,
  BaseSaleAttrResponseData,
  SpuSaleAttrValue,
} from '../../../api/product/spu/type'
import {
  reqAllTradeMark,
  reqSpuImg,
  reqSpuSaleAttr,
  reqAllSaleAttr,
  reqAddOrUpdateSpu,
} from '../../../api/product/spu/index'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
// 引入用户小仓库获取当前用户的Token 上传图片需要携带Token
import useUserStore from '../../../store/modules/user'
const userStore = useUserStore()
const headers = { Token: userStore.token }

// 存储已有的SPU对象
let SpuParams = ref<SpuData>({
  category3Id: 0, //收集三级分类的ID
  spuName: '', //SPU的名字
  description: '', //SPU的描述
  tmId: '', //品牌的ID
  spuImageList: [],
  spuSaleAttrList: [],
})

// 定义所有品牌的数据类型
let AllTradeMark = ref<TradeMarkData[]>([])
// 定义图片上传相关的变量
let imgList = ref<SpuImg[]>([])
// 定义已有的SPU销售属性的数据类型
let saleAttr = ref<SpuSaleValue[]>([])
// 定义全部的销售属性的数据类型
let allSaleAttr = ref<BaseSaleAttr[]>([])
let $emits = defineEmits(['changeScene'])

// 控制图片对话框的显示与隐藏
let dialogVisible = ref(false)

// 存储预览图片的地址
let dialogImageUrl = ref('')

//收集还未选择的当前SPU对应的销售属性id和名字
let unSelectSalkeAttrIdAndName = ref<string>('')

// 取消按钮
const cancel = () => {
  $emits('changeScene', { flag: 0, params: 'update' })
}

const initHasSpuData = async (spu: SpuData) => {
  // 初始化已有SPU的数据
  //存储已有的SPU对象,将来在模板中展示
  SpuParams.value = spu
  //spu:即为父组件传递过来的已有的SPU对象[不完整]
  //获取全部品牌的数据
  let result: AllTradeMarkResponseData = await reqAllTradeMark()
  //获取某一个品牌旗下全部售卖商品的图片
  let result1: SpuImgResponseData = await reqSpuImg(spu.id as number)
  //获取已有的SPU销售属性的数据
  let result2: SpuSaleResponseData = await reqSpuSaleAttr(spu.id as number)
  //获取整个项目全部SPU的销售属性
  let result3: BaseSaleAttrResponseData = await reqAllSaleAttr()
  //存储全部品牌的数据
  AllTradeMark.value = result.data
  //SPU对应商品图片
  imgList.value = result1.data.map((item): SpuImg => {
    return {
      name: item.imgName,
      url: item.imgUrl,
      id: item.id,
      spuId: item.spuId,
    }
  })
  //存储已有的SPU的销售属性
  saleAttr.value = result2.data
  //存储全部的销售属性
  allSaleAttr.value = result3.data
}

// 照片墙点击预览的钩子
const handlePictureCardPreview = (file: any) => {
  // 设置预览图片的地址
  dialogImageUrl.value = file.url
  // 当点击预览按钮的时候，弹出预览对话框按钮
  dialogVisible.value = true
}

// 照片墙删除图片的钩子
const handleRemove = () => {
  console.log('删除图片')
}

//照片钱上传成功之前的钩子约束文件的大小与类型
const handlerUpload = (file: any) => {
  if (
    file.type == 'image/png' ||
    file.type == 'image/jpeg' ||
    file.type == 'image/gif'
  ) {
    if (file.size / 1024 / 1024 < 3) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传文件务必小于3M',
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传文件务必PNG|JPG|GIF',
    })
    return false
  }
}

// 计算当前SPU还未拥有的销售属性
let unSelectSaleAttr = computed(() => {
  // filter:过滤出当前SPU还没有的销售属性
  let unSelectAttr = allSaleAttr.value.filter((item) => {
    return saleAttr.value.every((item1) => {
      return item.name != item1.saleAttrName
    })
  })
  return unSelectAttr
})

// 向已有的SPU销售属性中添加一个销售属性
const addSaleAttr = () => {
  /*
    "baseSaleAttrId": number,
    "saleAttrName": string,
    "spuSaleAttrValueList": SpuSaleAttrValueList
    */
  const [baseSaleAttrId, saleAttrName] =
    unSelectSalkeAttrIdAndName.value.split(':')
  //准备一个新的销售属性对象:将来带给服务器即可
  let newSaleAttr: SpuSaleValue = {
    baseSaleAttrId: Number(baseSaleAttrId),
    saleAttrName,
    spuSaleAttrValueList: [],
  }
  //追加到数组当中
  saleAttr.value.push(newSaleAttr)

  //清空收集的数据
  unSelectSalkeAttrIdAndName.value = ''
}

// 点击添加属性值按钮按钮 修改falge为true
const toEdito = (row: SpuSaleValue) => {
  row.flag = true
}

// 添加属性值输入框的bulr事件
const toLook = (row: SpuSaleValue) => {
  //整理收集的属性的ID与属性的名字
  const { baseSaleAttrId, saleAttrvalue } = row

  //准备一个新的销售属性值对象
  let newSaleAttrValue: SpuSaleAttrValue = {
    baseSaleAttrId,
    saleAttrValueName: row.saleAttrvalue as string,
  }
  //非法情况判断1
  if (row.saleAttrvalue?.trim() == '') {
    ElMessage({
      type: 'error',
      message: '属性值不能为空',
    })
    return
  }
  //非法情况2
  let repeat = row.spuSaleAttrValueList.find((item) => {
    return item.saleAttrValueName === row.saleAttrvalue
  })

  if (repeat) {
    //将重复的属性值从数组当中干掉
    row.saleAttrvalue = ''
    //提示信息
    ElMessage({
      type: 'error',
      message: '属性值不能重复',
    })
    return
  }

  //追加到当前SPU已有的销售属性对象的属性值数组当中
  row.spuSaleAttrValueList.push(newSaleAttrValue)
  //清空输入框数据
  row.saleAttrvalue = ''
  //相应的属性值对象flag:变为false,展示div
  row.flag = false
}

// 保存按钮回调事件
const save = async () => {
  //整理参数
  //发请求:添加SPU|更新已有的SPU
  //成功
  //失败
  //1:照片墙的数据
  SpuParams.value.spuImageList = imgList.value.map((item: any) => {
    return {
      imgName: item.name, //图片的名字
      imgUrl: (item.response && item.response.data) || item.url,
    }
  })
  //2:整理销售属性的数据
  SpuParams.value.spuSaleAttrList = saleAttr.value
  let result = await reqAddOrUpdateSpu(SpuParams.value)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: SpuParams.value.id ? '更新成功' : '添加成功',
    })
    //通知父组件切换场景为0
    $emits('changeScene', {
      flag: 0,
      params: SpuParams.value.id ? 'update' : 'add',
    })
  } else {
    ElMessage({
      type: 'error',
      message: SpuParams.value.id ? '更新失败' : '添加失败',
    })
  }
}

// 添加一个新的SPU初始化请求方法
const initAddSpu = async (c3Id: number) => {
  // 清空已有的数据
  Object.assign(SpuParams.value, {
    category3Id: 0, //收集三级分类的ID
    spuName: '', //SPU的名字
    description: '', //SPU的描述
    tmId: '', //品牌的ID
    spuImageList: [],
    spuSaleAttrList: [],
  })
  // 清除照片墙数据
  imgList.value = []
  // 清除已有销售属性对象数据
  saleAttr.value = []
  unSelectSalkeAttrIdAndName.value = ''
  // 存储三级分类的ID
  SpuParams.value.category3Id = c3Id

  // 获取所有的品牌数据
  let result: AllTradeMarkResponseData = await reqAllTradeMark()
  // 获取全部的销售属性
  let result1: BaseSaleAttrResponseData = await reqAllSaleAttr()

  // 存储全部的品牌数据
  AllTradeMark.value = result.data
  // 存储全部的销售属性
  allSaleAttr.value = result1.data
}
// 对父组件暴露该方法
defineExpose({ initHasSpuData, initAddSpu })
</script>

<style lang="scss" scoped></style>
